import { LANGUAGE_MAP } from "~/utils/const";
export const useAPI = (url, options) => {
    let langKey = "zh_tw";
    if (import.meta.server) {
        const cookies = useRequestHeaders(["cookie"]).cookie || "";
        const match = cookies.match(/i18n_redirected=([^;]+)/);
        langKey = match ? match[1] : "zh_tw";
        return useFetch(url, {
            baseURL: import.meta.env.VITE_BASE_URL,
            timeout: 10000,
            onRequest({ options: requestOptions }) {
                requestOptions.headers = {
                    "Accept-Language": LANGUAGE_MAP[langKey],
                    ...options?.headers,
                };
            },
            onResponse({ response }) {
                if (response.status >= 200 && response.status < 300) {
                    if (![0, 200].includes(response?._data?.code)) {
                        if (import.meta.client) {
                            ElMessage.error(response?._data?.msg);
                        }
                        return Promise.reject(response?._data);
                    }
                }
                return response._data;
            },
            onResponseError({ response }) {
                return Promise.reject(response?._data);
            },
            ...options,
        });
    }
    if (import.meta.client) {
        langKey = localStorage.getItem("lang") || "zh_tw";
        return $fetch(url, {
            baseURL: import.meta.env.VITE_BASE_URL,
            timeout: 10000,
            onRequest({ options: requestOptions }) {
                requestOptions.headers = {
                    "Accept-Language": LANGUAGE_MAP[langKey],
                    ...options?.headers,
                };
            },
            onResponse({ response }) {
                if (response.status >= 200 && response.status < 300) {
                    if (![0, 200].includes(response?._data?.code)) {
                        if (import.meta.client) {
                            ElMessage.error(response?._data?.msg);
                        }
                        return Promise.reject(response?._data);
                    }
                }
                return response._data;
            },
            onResponseError({ response }) {
                return Promise.reject(response?._data);
            },
            ...options,
        });
    }
};

export const useGET = async (url, options) => {
    const result = await useAPI(url, {
        method: "GET",
        ...options,
    });
    const res = import.meta.server ? result.data.value : result;
    return res;
};

export const usePOST = async (url, options) => {
    const result = await useAPI(url, {
        method: "POST",
        body: { ...options.query },
        ...options,
    });
    const res = import.meta.server ? result.data.value : result;
    return res;
};
